<template>
  <div ref="canvas"></div>
</template>

<script lang="ts" setup>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js";
import { ref, onMounted } from "vue";
import {initDefaultLighting} from "@/book/ThreeUtils";

const canvas = ref();

const scene = new THREE.Scene()

const renderer = new THREE.WebGLRenderer()
renderer.setClearColor(0x000000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
camera.position.set(-30, 40, 30);
camera.lookAt(0, 0, 0,);

const orbitControl = new OrbitControls(camera, renderer.domElement);

const stat = Stats();

const planeGeometry = new THREE.PlaneGeometry(1000, 1000);
const planeMaterial = new THREE.MeshPhongMaterial({
  color: 0xffffff
});
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.receiveShadow = true;
plane.rotateX(- Math.PI / 2);
plane.position.set(0, -30, 0);
scene.add(plane);

initDefaultLighting(scene, undefined);

const controls = {
  amount : 2,
  bevelThickness : 2,
  bevelSize : 0.5,
  bevelEnabled : true,
  bevelSegments : 3,
  curveSegments : 12,
  steps : 1,
};

const shape = drawShape();
const extrude = new THREE.ExtrudeGeometry(shape, controls);
extrude.applyMatrix4(new THREE.Matrix4().makeTranslation(-20, 0, 0));
extrude.applyMatrix4(new THREE.Matrix4().makeScale(0.4,0.4,0.4));

const mesh = new THREE.Mesh(extrude);
scene.add(mesh);

const render = () => {
  stat.update();
  orbitControl.update();

  requestAnimationFrame(render);
  renderer.render(scene, camera);
};

onMounted(() => {
  canvas.value.appendChild(stat.domElement);
  canvas.value.appendChild(renderer.domElement);

  render();
});

function drawShape() {
  const shape = new THREE.Shape();

  // 起点
  shape.moveTo(10, 10);
  // 起始线段
  shape.lineTo(10, 40);
  // 图的顶部, 向右弯曲 - 前四个分别是两个控制点的x,y坐标，最后两个是终止点的x,y坐标
  shape.bezierCurveTo(15, 25, 25, 25, 30, 40);

  // 将二维点的数组以曲线连接起来，形成一条平滑曲线。
  shape.splineThru([
    new THREE.Vector2(32, 30),
    new THREE.Vector2(28, 20),
    new THREE.Vector2(30, 10),
  ]);

  shape.quadraticCurveTo(20, 15, 10, 10);

  const rightEye = new THREE.Path();
  rightEye.absellipse(16, 24, 2, 3, 0, Math.PI * 2, true);
  shape.holes.push(rightEye);

  const leftEye = new THREE.Path();
  leftEye.absellipse(23, 24, 2, 3, 0, Math.PI * 2, true);
  shape.holes.push(leftEye);

  const mouth = new THREE.Path();
  mouth.absarc(20, 16, 2, 0, Math.PI, true);
  shape.holes.push(mouth);

  return shape;
}


</script>
